﻿using AppUpdate.Utils;
using CL.IO.Zip;
using Newtonsoft.Json;
using Rubyer;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace AppUpdate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        string fileName = AppDomain.CurrentDomain.BaseDirectory + @"\" + "video621.mp4";
        Entity.Parameters Pairs = new Entity.Parameters();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaPlayer.Source = new Uri(MediaPlayer.Source.ToString());
            MediaPlayer.Play();
        }

        public MainWindow(string[] args)
        {
            InitializeComponent();

            FileHelper.ByteToFile(Resource.video621, fileName);
            MediaPlayer.Source = new Uri(fileName);
            MediaPlayer.Play();
            if (args != null && args.Length > 0)
            {
                Pairs = JsonConvert.DeserializeObject<Entity.Parameters>(args[0]);
            }
            else
            {
                Pairs = JsonConvert.DeserializeObject<Entity.Parameters>("{\"Image\":[\"https://pic.imgdb.cn/item/6422a45ca682492fcc7f4f25.png\",\"https://pic.imgdb.cn/item/6422a45ca682492fcc7f4f9e.png\"],\"DownloadAddress\":\"\",\"AppPath\":\"\",\"DeleteFilePath\":[],\"ExePath\":\"\"}");
                //Pairs = JsonConvert.DeserializeObject<Entity.Parameters>("{\"Image\":[\"https://gitee.com/ykyangkun/ui-path-management-tool/raw/master/image-2.png\",\"https://gitee.com/ykyangkun/ui-path-management-tool/raw/master/image-1.png\"],\"DownloadAddress\":\"http://yuangu.test.upcdn.net/%E9%98%BF%E9%87%8C%E4%BA%91%E7%9B%98%E5%B0%8F%E7%99%BD%E7%BE%8A%E7%89%88v2.zip\",\"AppPath\":\"E:\\\\工具\\\\阿里云盘小白羊版v2\",\"DeleteFilePath\":[\"chrome_100_percent.pak\",\"chrome_200_percent.pak\",\"d3dcompiler_47.dll\",\"ffmpeg.dll\",\"icudtl.dat\",\"阿里云盘小白羊版v2.exe\"],\"ExePath\":\"阿里云盘小白羊版v2.exe\"}");
            }
            List<Image> images = new List<Image>();
            foreach (var item in Pairs.Image)
            {
                BitmapImage bitImage = new BitmapImage();
                bitImage.BeginInit();
                bitImage.UriSource = new Uri(item, UriKind.Absolute);
                bitImage.EndInit();
                Image img = new Image() { Source = bitImage, Width = 800 };
                images.Add(img);
            }
            Shuffling_Carousel.ItemsSource = images;
        }

        private void ProgressBar_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
                DragMove();
        }

        private void ShutDown_Click(object sender, System.Windows.RoutedEventArgs e)
        {

            GC.Collect();

            Environment.Exit(0);
        }

        /// <summary>
        /// 计算文件大小函数(保留两位小数),Size为字节大小
        /// </summary>
        /// <param name="size">初始文件大小</param>
        /// <returns></returns>
        public static string GetFileSize(long size)
        {
            var num = 1024.00; //byte
            if (size < num)
                return size + "B";
            if (size < Math.Pow(num, 2))
                return (size / num).ToString("f2") + "K"; //kb
            if (size < Math.Pow(num, 3))
                return (size / Math.Pow(num, 2)).ToString("f2") + "M"; //M
            if (size < Math.Pow(num, 4))
                return (size / Math.Pow(num, 3)).ToString("f2") + "G"; //G

            return (size / Math.Pow(num, 4)).ToString("f2") + "T"; //T
        }

        private void TheUpdate_Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ButtonFunction.Visibility = System.Windows.Visibility.Hidden;
            UpdateState.Visibility = System.Windows.Visibility.Visible;

            //修改界面状态
            FileName.Text = "下载更新文件";
            FileCount.Text = "1/1";
            UpdateProgress.Value = 0;


            if (!string.IsNullOrEmpty(Pairs.ProcName))
            {
                TheThreeOperationHelper.CloseProc(Pairs.ProcName);
            }

            Thread thread = new Thread(() =>
            {
                TheNetworkFile theNetworkFile = new TheNetworkFile();
                theNetworkFile.DownloadFile(Pairs.DownloadAddress, Pairs.AppPath + "Update.zip", (int TheProgressOf, long totalDownloadedByte, long totalBytes) =>
                {
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        UpdateProgress.Value = TheProgressOf;
                        FileCount.Text = $"{GetFileSize(totalDownloadedByte)}/{GetFileSize(totalBytes)}";
                    }));
                });

                if (Pairs.DeleteFilePath != null && Pairs.DeleteFilePath.Count > 0)
                {
                    int deleteCout = 0;
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        FileName.Text = "正在删除文件";
                        FileCount.Text = $"0/{Pairs.DeleteFilePath.Count}";
                        UpdateProgress.Value = 0;
                    }));
                    foreach (var item in Pairs.DeleteFilePath)
                    {
                        deleteCout++;
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FileCount.Text = $"{deleteCout}/{Pairs.DeleteFilePath.Count}";
                            UpdateProgress.Value = deleteCout / Pairs.DeleteFilePath.Count * 100;
                        }));
                        try
                        {
                            File.Delete(Pairs.AppPath + "\\" + item);
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    FileName.Text = "正在解压更新文件";
                    FileCount.Text = "";
                    UpdateProgress.Value = 0;
                }));
                //DirectoryInfo directoryInfo = new(Pairs.AppPath + "Update.zip");
                //if (!directoryInfo.Exists)
                //{
                //    directoryInfo.Create();
                //}
                //ZipFile.ExtractToDirectory(Pairs.AppPath, Pairs.AppPath + "Update.zip");
                ZipHandler handler = ZipHandler.GetInstance();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                handler.UnpackAll(Pairs.AppPath + "Update.zip", Pairs.AppPath, (num) =>
                {
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        UpdateProgress.Value = num;
                    }));
                });
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    FileName.Text = "更新完成";
                    System.Threading.Tasks.Task<MessageBoxResult> messbox = MessageBoxR.Success("更新完成", button: MessageBoxButton.OK);
                    if (!string.IsNullOrEmpty(Pairs.ExePath))
                    {
                        Process.Start(Pairs.AppPath + "\\" + Pairs.ExePath);
                    }
                }));

            });
            thread.Start();
        }




    }
}
